package com.sctvcloud.renhe.base;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentManager;
import android.text.TextUtils;

import com.jiongbull.jlog.JLog;
import com.ruihang.generalibrary.ui.dialog.ShareFragment;
import com.ruihang.generalibrary.utils.IShares;
import com.ruihang.generalibrary.utils.ResultAsyncTask;
import com.ruihang.generalibrary.utils.TimeObserve;
import com.sctvcloud.renhe.R;
import com.sctvcloud.renhe.application.Cache;
import com.sctvcloud.renhe.application.Constances;
import com.sctvcloud.renhe.beans.CommentTemp;
import com.sctvcloud.renhe.beans.FComment;
import com.sctvcloud.renhe.beans.FocusColumn;
import com.sctvcloud.renhe.http.AbsListNetCallback;
import com.sctvcloud.renhe.http.NetUtils;
import com.sctvcloud.renhe.ui.activities.RebllionCommitActivity;
import com.sctvcloud.renhe.ui.dialog.CommentDiaFragment;
import com.sctvcloud.renhe.ui.utils.CollectionUtils;
import com.sctvcloud.renhe.ui.utils.KeyBoardUtils;
import com.sctvcloud.renhe.ui.utils.SkipUtil;
import com.sctvcloud.renhe.utils.ListTypeUtils;

import java.util.ArrayList;
import java.util.List;

import butterknife.Unbinder;

/**
 * Created by rh008 on 2017/7/17.
 * 新闻详情、专题详情等页面的基类。（在此页面进行了评论列表的请求）
 */

public class BaseDetailActivity extends BaseActivity {
    protected ShareFragment shareFragment;
    public static final String SHARE_TAG = "share_fragment";

    public static final String COMMENT_TAG = "dia_comment_fragment";

    protected String baseUrl;

    private CommentTemp commentTemp;

    protected Handler mHandler;

    private String newsId;
    private int typeName = 0;//新闻、直播类型

    /**
     * 评论的频道信息
     */
    protected FocusColumn commentColumn;

    protected CommentDiaFragment commentDiaFragment;

    protected int commentType;

    protected Unbinder butterUnbinder;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        baseUrl = getIntent().getStringExtra(EX_URL);
        mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                if (msg != null) {
                    parseHanldeMsg(msg);
                }
            }
        };
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    protected void onDestroy() {
        if (butterUnbinder != null) {
            butterUnbinder.unbind();
        }
        super.onDestroy();
        TimeObserve.removeObserS(getOwnerName() + SHARE_TAG, getOwnerName() + COMMENT_TAG);
    }

    @Override
    protected void onLoginUnSuc() {
        if (commentTemp != null) {
            toast(R.string.please_login_first);
            commentTemp = null;
        }
    }

    private CommentDiaFragment.SendComment sendComment = new CommentDiaFragment.SendComment() {
        @Override
        public boolean onCommentSendPrepare(int mode) {
            return onCommentNetPrepare(mode);
        }

        @Override
        public void onCommentSendSuccess(int mode) {
            SkipUtil.skipToAddUserOperate(BaseDetailActivity.this, getOwnerName(),   12, typeName, "提交评论成功", newsId, Cache.getInstance().getCurrentChannelId());
            addInvitation(Constances.ADD_INTEGRAL_COMMENT, false);
            onCommentSendSuc(mode);
        }

        @Override
        public void onCommentSendFinish(int mode, boolean isNetSuc) {

        }
    };

    protected void parseHanldeMsg(@NonNull Message msg) {
    }

    protected void onLoginSuc() {
    }

    protected void getConmmentSendBackMsg(String msg) {
        KeyBoardUtils.closeKeyboard(this);
        if (!TextUtils.isEmpty(msg)) {
            toast("发送评论" + msg);
        }
    }

    protected synchronized void showShareFragment(IShares iShares, ShareFragment.OnShareFragmentClickListener onShareFragmentClickListener) {
//        if (shareFragment == null) {
        shareFragment = new ShareFragment();
//        }
//        if (shareFragment.isAdded() || TimeObserve.isEarlyS(getOwnerName() + SHARE_TAG, 50)) {
//            return;
//        }
        shareFragment.setShares(iShares);
        shareFragment.setOnShareFragmentClickListener(onShareFragmentClickListener);
        shareFragment.setShareSuccessListener(new ShareFragment.ShareSuccess() {
            @Override
            public void OnShareSuccess(String shareType) {
                addInvitation(Constances.ADD_INTEGRAL_FORWARD, false);
                SkipUtil.skipToAddUserOperate(BaseDetailActivity.this, getOwnerName(),   14, typeName, shareType, newsId, Cache.getInstance().getCurrentChannelId());

            }
        });
        FragmentManager fm = getSupportFragmentManager();
        shareFragment.show(fm, SHARE_TAG);
        fm.executePendingTransactions();
    }

    protected boolean getCommentNews(String id, int requestType, int capacity, int index) {
        if (!onCommentNetPrepare(Constances.MODE_COMMENT_GET_NEW)) {
            return false;
        }
        NetUtils.getNetAdapter().getCommentList(getOwnerName(), id, requestType, capacity, index
                , new AbsListNetCallback<FComment>(ListTypeUtils.FProgramme()) {
                    private boolean isSuc;

                    @Override
                    public void onSuc(List<FComment> fProgrammes) {
                        JLog.e("get comment suc\n  " + fProgrammes);
                        onCommentGetListSuc(getPageResponse().getData().getCommentCount(), fProgrammes);
                        isSuc = true;
                    }

                    @Override
                    public void onError(Throwable ex, String errorMsg) {
                        super.onError(ex, errorMsg);
                        JLog.e("===error==" + errorMsg);
                    }

                    @Override
                    public void onEnd() {
                        super.onEnd();
                        onCommentNetFinish(Constances.MODE_COMMENT_GET_NEW, isSuc);
                    }
                });
        return true;
    }

    protected boolean getCommentNews(String id, String url, int requestType, int capacity, int index) {
        if (!onCommentNetPrepare(Constances.MODE_COMMENT_GET_NEW)) {
            return false;
        }
        NetUtils.getNetAdapter().getCommentList(getOwnerName(), url + "getCommentList", id, requestType, capacity, index
                , new AbsListNetCallback<FComment>(ListTypeUtils.FProgramme()) {
                    private boolean isSuc;

                    @Override
                    public void onSuc(List<FComment> fProgrammes) {
                        JLog.e("get comment suc\n  " + fProgrammes);
                        onCommentGetListSuc(getPageResponse().getData().getCommentCount(), fProgrammes);
                        isSuc = true;
                    }

                    @Override
                    public void onError(Throwable ex, String errorMsg) {
                        super.onError(ex, errorMsg);
                        JLog.e("===error==" + errorMsg);
                    }

                    @Override
                    public void onEnd() {
                        super.onEnd();
                        onCommentNetFinish(Constances.MODE_COMMENT_GET_NEW, isSuc);
                    }
                });
        return true;
    }

    protected void onCommentGetListSuc(int count, List<FComment> fProgrammes) {
    }

    protected void onCommentNetFinish(int mode, boolean isNetSuc) {
    }

    protected void onCommentSendSuc(int mode) {
    }

    protected boolean onCommentNetPrepare(int mode) {
        return true;
    }

    protected synchronized void showCommentDialog(String newsId, String commentId, int types) {
        JLog.e("newsId =" + newsId + "   commentId=" + commentId);
        if (TextUtils.isEmpty(newsId)) {
            toast(R.string.data_wrong);
            return;
        }
        FragmentManager fm = getSupportFragmentManager();
//        if (commentDiaFragment == null) {
        commentDiaFragment = new CommentDiaFragment();
        commentDiaFragment.setSendComment(sendComment);
        commentDiaFragment.setCommentType(types);
        this.newsId = newsId;
//        }
//        if (commentDiaFragment.isAdded() || TimeObserve.isEarlyS(getOwnerName() + COMMENT_TAG, 50)) {
//            return;
//        }
        commentDiaFragment.setInfo(newsId, commentId);
        commentDiaFragment.setTypes(types);
        commentDiaFragment.show(fm, COMMENT_TAG);
        fm.executePendingTransactions();
    }

    protected synchronized void showCommentDialog(String newsId, boolean isLuzhou, String commentId, int types) {
        JLog.e("newsId =" + newsId + "   commentId=" + commentId);
        if (TextUtils.isEmpty(newsId)) {
            toast(R.string.data_wrong);
            return;
        }
        FragmentManager fm = getSupportFragmentManager();
//        if (commentDiaFragment == null) {
        commentDiaFragment = new CommentDiaFragment();
        commentDiaFragment.setSendComment(sendComment);
        commentDiaFragment.setLuzhow(isLuzhou);
        commentDiaFragment.setCommentType(types);
        this.newsId = newsId;
//        }
//        if (commentDiaFragment.isAdded() || TimeObserve.isEarlyS(getOwnerName() + COMMENT_TAG, 50)) {
//            return;
//        }
        commentDiaFragment.setInfo(newsId, commentId);
        commentDiaFragment.setTypes(types);
        commentDiaFragment.show(fm, COMMENT_TAG);
        fm.executePendingTransactions();
    }

    /**
     * 日志统计中的新闻类型
     * @param typeName
     */
    public void setTypeName(int typeName) {
        this.typeName = typeName;
    }

    /**
     * 日志统计需要的新闻或直播等的ID
     * @param newsId
     */
    public void setNewsId(String newsId) {
        this.newsId = newsId;
    }

    protected void checkCollect(String id) {
        if (TextUtils.isEmpty(id)) {
            onCollectCheckResult(-1);
            return;
        }
        new ResultAsyncTask<Integer>(id) {
            @Override
            protected Integer doInBackground(Void... params) {
                return CollectionUtils.getInstance().isCollected(logTag) ? 1 : 0;
            }

            @Override
            protected void onPostExecute(Integer aBoolean) {
                onCollectCheckResult(aBoolean);
            }
        }.ex();
    }

    protected void onCollectCheckResult(int result) {
    }

}
